package ru.agiledev.akb.server.util;

import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;
import ru.agiledev.akb.server.domain.presentation.Author;
import ru.agiledev.akb.server.hibernate.HibernateUtil;

import java.security.NoSuchAlgorithmException;
import java.util.List;

/**
 * Created by a.kirillov
 * Date: 4/3/11 Time: 12:25 PM
 */
public class AuthenticationManager {

    public static Author authenticateUser(String login, String password){
        Session session = HibernateUtil.getSessionFactory().openSession();

        String encriptedPassword = "";

        try {
            encriptedPassword = HashUtils.createSHA256(password);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }

        List users = session.createCriteria(Author.class).add(Restrictions.eq("login", login)).add(Restrictions.eq("password", encriptedPassword)).list();
        if(users.size() == 0){
            return null;
        } else {
            if(users.size()==1){
                Author author = (Author)users.get(0);
                session.close();
                return author;
            }
        }
        session.close();
        return null;
    }
}
